<?php
namespace Wap\Controller;
use Think\Controller;

class CheckwxController extends Controller {
	
	public function index()
	{
		$sysconfig = M('sys_config')->find();
		$secd = (int)$sysconfig['youxichecksec']>0?(int)$sysconfig['youxichecksec']:30;
		$this->secd = $secd*1000;
		if(!$sysconfig['youxiurl'])
		{
			$this->msgd = '没有要跳转的域名';
		}
		else
		{
			$allyouxiurl = explode("\n", str_replace("\r\n", "\n", $sysconfig['youxiurl']));
			/* foreach($allyouxiurl as $k => $url)
			{
				if(!$url)
				{
					unset($allyouxiurl[$k]);
					continue;
				}
			} */
			if(empty($allyouxiurl))
			{
				$this->msgd = '没有要跳转的域名';
			}
			else
			{
				if(!$this->do_check($allyouxiurl[0],$sysconfig['youxicheckkey']))
				{
					$hhh = str_replace($url,'',$sysconfig['youxiurl']);
					$hhh = trim($hhh,'\r\n');
					$hhh = trim($hhh,'\n');
					M('sys_config')->save(array('youxiurl'=>$hhh,'id'=>1));
					$this->msgd = '域名不可用，正在使用下一域名中。';
				}
				else
				{
					$this->msgd = '域名正常运行中，请不要关闭此页面。';
				}
				
			}
		}
		$this->display();
    }
	
	private function do_check($url,$token){
		$api_url = 'http:///wz5.tkc8.com/manage/api/check?token='.$token.'&url='.$url;
		$content = $this->get_msg($api_url);
		$data = json_decode($content,true);
		//var_dump($data);die;
		if($data['code']==9904){
			return false;
		}else{
			return true;
		}
	}
	
	private function get_msg($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,5);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
		}
	}
}
?>